<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <div class="logo-circle">
            <i class="logo-icon">📝</i>
          </div>
          <h1>三角洲创作中心</h1>
          <p class="subtitle">欢迎回来，请登录您的账户</p>
        </div>

        <form class="login-form" @submit.prevent="handleLogin">
          <div class="form-group">
            <label>
              <i class="icon">👤</i>
              用户名
            </label>
            <input
              v-model="loginForm.username"
              type="text"
              placeholder="请输入用户名"
              required
              autocomplete="username"
            />
          </div>

          <div class="form-group">
            <label>
              <i class="icon">🔒</i>
              密码
            </label>
            <div class="password-input">
              <input
                v-model="loginForm.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                required
                autocomplete="current-password"
              />
              <button
                type="button"
                class="toggle-password"
                @click="showPassword = !showPassword"
              >
                <i class="icon">{{ showPassword ? '👁️' : '👁️‍🗨️' }}</i>
              </button>
            </div>
          </div>

          <div class="form-options">
            <label class="remember-me">
              <input type="checkbox" v-model="loginForm.rememberMe" />
              <span>记住我</span>
            </label>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>

          <button type="submit" class="btn-login" :disabled="isLoading">
            <span v-if="!isLoading">
              <i class="icon">🚀</i>
              登录
            </span>
            <span v-else>
              <i class="icon loading">⏳</i>
              登录中...
            </span>
          </button>
        </form>

        <div class="login-footer">
          <p>还没有账户？<router-link to="/register" class="register-link">立即注册</router-link></p>
        </div>


      </div>

      <div class="decoration-circles">
        <div class="circle circle-1"></div>
        <div class="circle circle-2"></div>
        <div class="circle circle-3"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../api/auth'
import { getUserMenus } from '../api/user'
import toast from '../utils/toast'
import { addDynamicRoutes } from '../router'
import { getFirstMenuPath } from '../utils/routerHelper'

const router = useRouter()

const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false
})

const showPassword = ref(false)
const isLoading = ref(false)

// 页面加载时恢复"记住我"的信息
onMounted(() => {
  const rememberMe = localStorage.getItem('rememberMe')
  if (rememberMe === 'true') {
    const savedUsername = localStorage.getItem('savedUsername')
    const savedPassword = localStorage.getItem('savedPassword')
    
    if (savedUsername) {
      loginForm.value.username = savedUsername
    }
    if (savedPassword) {
      loginForm.value.password = savedPassword
    }
    loginForm.value.rememberMe = true
  }
})

const handleLogin = async () => {
  // 表单验证
  if (!loginForm.value.username.trim()) {
    toast.error('请输入用户名')
    return
  }

  if (!loginForm.value.password.trim()) {
    toast.error('请输入密码')
    return
  }

  // 开始登录
  isLoading.value = true

  try {
    // 调用登录接口
    const result = await login({
      username: loginForm.value.username,
      password: loginForm.value.password,
      confirmPassword: loginForm.value.password
    })

    // 登录成功，保存token和用户信息
    if (result.code === 200 && result.data) {
      const { accessToken, refreshToken, userInfo, menus, permissions, roles } = result.data
      
      // 保存登录状态
      localStorage.setItem('isLoggedIn', 'true')
      
      // 保存 token
      if (accessToken) {
        localStorage.setItem('accessToken', accessToken)
      }
      if (refreshToken) {
        localStorage.setItem('refreshToken', refreshToken)
      }
      
      // 保存用户信息
      if (userInfo) {
        localStorage.setItem('username', userInfo.username)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      }
      
      // 保存权限和角色
      if (permissions) {
        sessionStorage.setItem('userPermissions', JSON.stringify(permissions))
      }
      if (roles) {
        sessionStorage.setItem('userRoles', JSON.stringify(roles))
      }
      
      // 记住我选项
      if (loginForm.value.rememberMe) {
        localStorage.setItem('rememberMe', 'true')
        localStorage.setItem('savedUsername', loginForm.value.username)
        localStorage.setItem('savedPassword', loginForm.value.password)
      } else {
        // 如果不记住，清除保存的信息
        localStorage.removeItem('rememberMe')
        localStorage.removeItem('savedUsername')
        localStorage.removeItem('savedPassword')
      }

      // 获取用户菜单
      let userMenus = menus
      
      // 如果登录接口没有返回菜单，则调用菜单接口获取
      if (!userMenus || userMenus.length === 0) {
        try {
          const menuResult = await getUserMenus()
          if (menuResult.code === 200 && menuResult.data) {
            userMenus = menuResult.data
          }
        } catch (error) {
          console.error('获取菜单失败:', error)
        }
      }

      // 添加动态路由
      if (userMenus && userMenus.length > 0) {
        addDynamicRoutes(userMenus)
        
        // 获取第一个菜单路径并跳转
        const firstPath = getFirstMenuPath(userMenus)
        toast.success('登录成功！')
        router.push(firstPath)
      } else {
        // 没有菜单权限
        toast.warning('您暂无任何菜单权限，请联系管理员')
        // 清除登录信息
        localStorage.removeItem('isLoggedIn')
        localStorage.removeItem('accessToken')
      }
    } else {
      toast.error(result.message || '登录失败')
    }
  } catch (error) {
    // 登录失败
    console.error('登录错误:', error)
    toast.error('登录失败：' + (error.message || '请检查用户名和密码'))
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-container {
  position: relative;
  z-index: 10;
  width: 100%;
  max-width: 450px;
}

.login-card {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: slideUp 0.5s ease;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 35px;
}

.logo-circle {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.logo-icon {
  font-size: 40px;
  font-style: normal;
}

.login-header h1 {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 10px;
  font-weight: 700;
}

.subtitle {
  color: #7f8c8d;
  font-size: 15px;
  margin: 0;
}

.icon {
  font-style: normal;
}

.login-form {
  margin-bottom: 25px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #555;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  font-size: 15px;
  transition: all 0.3s;
  font-family: inherit;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
}

.password-input {
  position: relative;
}

.password-input input {
  padding-right: 45px;
}

.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 18px;
  color: #7f8c8d;
  transition: all 0.3s;
  padding: 5px;
}

.toggle-password:hover {
  color: #667eea;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  font-size: 14px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #555;
}

.remember-me input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #667eea;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  transition: all 0.3s;
}

.forgot-password:hover {
  color: #764ba2;
  text-decoration: underline;
}

.btn-login {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.btn-login:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}

.btn-login:active:not(:disabled) {
  transform: translateY(0);
}

.btn-login:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.login-footer {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
  color: #7f8c8d;
  font-size: 14px;
}

.register-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
  margin-left: 5px;
  transition: all 0.3s;
}

.register-link:hover {
  color: #764ba2;
  text-decoration: underline;
}

.demo-info {
  margin-top: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 10px;
  text-align: center;
}

.demo-title {
  font-weight: 600;
  color: #555;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.demo-account {
  color: #666;
  font-size: 13px;
  margin: 4px 0;
  font-family: 'Courier New', monospace;
}

/* 装饰圆圈 */
.decoration-circles {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  overflow: hidden;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 20s ease-in-out infinite;
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -150px;
  left: -150px;
  animation-delay: 0s;
}

.circle-2 {
  width: 200px;
  height: 200px;
  bottom: -100px;
  right: -100px;
  animation-delay: 5s;
}

.circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  right: -75px;
  animation-delay: 10s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-page {
    padding: 15px;
  }

  .login-card {
    padding: 35px 30px;
  }

  .login-header h1 {
    font-size: 26px;
  }

  .form-group input {
    font-size: 16px; /* 防止 iOS 自动缩放 */
  }

  .demo-info {
    margin-top: 15px;
    padding: 12px;
  }

  .demo-account {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .login-page {
    padding: 10px;
  }

  .login-card {
    padding: 25px 20px;
    border-radius: 15px;
  }

  .login-header {
    margin-bottom: 25px;
  }

  .login-header h1 {
    font-size: 22px;
  }

  .subtitle {
    font-size: 13px;
  }

  .logo-circle {
    width: 65px;
    height: 65px;
    margin-bottom: 15px;
  }

  .logo-icon {
    font-size: 32px;
  }

  .form-group {
    margin-bottom: 16px;
  }

  .form-group label {
    font-size: 13px;
    margin-bottom: 6px;
  }

  .form-group input {
    padding: 11px 14px;
    font-size: 16px; /* 防止 iOS 自动缩放 */
  }

  .password-input input {
    padding-right: 40px;
  }

  .form-options {
    font-size: 13px;
    margin-bottom: 20px;
  }

  .btn-login {
    padding: 12px;
    font-size: 15px;
  }

  .login-footer {
    font-size: 13px;
  }

  .demo-info {
    padding: 10px;
  }

  .demo-title {
    font-size: 13px;
  }

  .demo-account {
    font-size: 11px;
  }
}

@media (max-width: 360px) {
  .login-card {
    padding: 20px 15px;
  }

  .login-header h1 {
    font-size: 20px;
  }

  .logo-circle {
    width: 60px;
    height: 60px;
  }
}
</style>
